package com.yipinsoft.modules.wechat.core.web;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * 微信菜单操作
 * @author liulin
 *
 */
@RestController
@RequestMapping("${wechatPath}/oauth")
public class WechatOauth2Controller {

	private static final String WECHAT_USER_CACHE = "wechatUserCache";
	
   /**
    * 微信oauth认证连接（当使用前后端分离结构时可以使用本函数）
    * @param request
    * @param response
    * @return
    * @throws WxErrorException
    * @throws IOException
    */
    @RequestMapping(value = "/authorization", method = RequestMethod.GET)
    public String authorization(HttpServletRequest request, HttpServletResponse response) throws WxErrorException, IOException {
    	String sessionId = request.getSession().getId();
    	
    	if(StringUtils.isBlank(sessionId)) {
    		return "sessionId为空";
    	}
    	
    	WxMpUser wxMpUser = (WxMpUser)CacheUtils.get(WECHAT_USER_CACHE, sessionId);
		CacheUtils.put(WECHAT_USER_CACHE, wxMpUser.getOpenId(), wxMpUser);
		response.sendRedirect("http://www.plusdo.com?openid="+ wxMpUser.getOpenId());
		return "";
    	
    	
    }
    
    /**
     * 微信授权认证常规(页面和后台在一起)方法，由拦截器完成微信授权认证
     * @param request
     * @param response
     * @return
     * @throws WxErrorException
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, HttpServletResponse response) throws WxErrorException {
    	String sessionId = request.getSession().getId();
    	
    	if(StringUtils.isBlank(sessionId)) {
    		return "sessionId为空";
    	}
    	
    	WxMpUser wxMpUser = (WxMpUser)CacheUtils.get(WECHAT_USER_CACHE, sessionId);
    	
    	if(wxMpUser != null) {
    		return wxMpUser.toString();
    	}
    	
    	return "";
    }
}
